home *** CD-ROM | disk | FTP | other *** search
/ Visual Cafe 3 / Visual Cafe 3.ISO / Vcafe / Main.bin / DigitList.java < prev    next >
Text File  |  1998-09-22  |  21KB  |  537 lines

  1. /*
  2.  * @(#)DigitList.java    1.13 98/01/12
  3.  *
  4.  * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
  5.  * (C) Copyright IBM Corp. 1996 - All Rights Reserved
  6.  *
  7.  * Portions copyright (c) 1996 Sun Microsystems, Inc. All Rights Reserved.
  8.  *
  9.  *   The original version of this source code and documentation is copyrighted
  10.  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  11.  * materials are provided under terms of a License Agreement between Taligent
  12.  * and Sun. This technology is protected by multiple US and International
  13.  * patents. This notice and attribution to Taligent may not be removed.
  14.  *   Taligent is a registered trademark of Taligent, Inc.
  15.  *
  16.  * Permission to use, copy, modify, and distribute this software
  17.  * and its documentation for NON-COMMERCIAL purposes and without
  18.  * fee is hereby granted provided that this copyright notice
  19.  * appears in all copies. Please refer to the file "copyright.html"
  20.  * for further important copyright and licensing information.
  21.  *
  22.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  23.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  24.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  25.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  26.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  27.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  28.  *
  29.  */
  30.  
  31. package java.text;
  32.  
  33. /**
  34.  * Digit List. Private to DecimalFormat.
  35.  * Handles the transcoding
  36.  * between numeric values and strings of characters.  Only handles
  37.  * non-negative numbers.  The division of labor between DigitList and
  38.  * DecimalFormat is that DigitList handles the radix 10 representation
  39.  * issues; DecimalFormat handles the locale-specific issues such as
  40.  * positive/negative, grouping, decimal point, currency, and so on.
  41.  *
  42.  * A DigitList is really a representation of a floating point value.
  43.  * It may be an integer value; we assume that a double has sufficient
  44.  * precision to represent all digits of a long.
  45.  *
  46.  * The DigitList representation consists of a string of characters,
  47.  * which are the digits radix 10, from '0' to '9'.  It also has a radix
  48.  * 10 exponent associated with it.  The value represented by a DigitList
  49.  * object can be computed by mulitplying the fraction f, where 0 <= f < 1,
  50.  * derived by placing all the digits of the list to the right of the
  51.  * decimal point, by 10^exponent.
  52.  *
  53.  * @see  Locale
  54.  * @see  Format
  55.  * @see  NumberFormat
  56.  * @see  DecimalFormat
  57.  * @see  ChoiceFormat
  58.  * @see  MessageFormat
  59.  * @version      1.13 01/12/98
  60.  * @author       Mark Davis, Alan Liu
  61.  */
  62. final class DigitList implements Cloneable {
  63.     /**
  64.      * The maximum number of significant digits in an IEEE 754 double, that
  65.      * is, in a Java double.  This must not be increased, or garbage digits
  66.      * will be generated, and should not be decreased, or accuracy will be lost.
  67.      */
  68.     public static final int MAX_COUNT = 19; // == Long.toString(Long.MAX_VALUE).length()
  69.     public static final int DBL_DIG = 17;
  70.  
  71.     /**
  72.      * These data members are intentionally public and can be set directly.
  73.      *
  74.      * The value represented is given by placing the decimal point before
  75.      * digits[decimalAt].  If decimalAt is < 0, then leading zeros between
  76.      * the decimal point and the first nonzero digit are implied.  If decimalAt
  77.      * is > count, then trailing zeros between the digits[count-1] and the
  78.      * decimal point are implied.
  79.      *
  80.      * Equivalently, the represented value is given by f * 10^decimalAt.  Here
  81.      * f is a value 0.1 <= f < 1 arrived at by placing the digits in Digits to
  82.      * the right of the decimal.
  83.      *
  84.      * DigitList is normalized, so if it is non-zero, figits[0] is non-zero.  We
  85.      * don't allow denormalized numbers because our exponent is effectively of
  86.      * unlimited magnitude.  The count value contains the number of significant
  87.      * digits present in digits[].
  88.      *
  89.      * Zero is represented by any DigitList with count == 0 or with each digits[i]
  90.      * for all i <= count == '0'.
  91.      */
  92.     public int decimalAt = 0;
  93.     public int count = 0;
  94.     public byte[] digits = new byte[MAX_COUNT];
  95.  
  96.     /**
  97.      * Return true if the represented number is zero.
  98.      */
  99.     boolean isZero()
  100.     {
  101.         for (int i=0; i<count; ++i) if (digits[i] != '0') return false;
  102.         return true;
  103.     }
  104.  
  105.     /**
  106.      * Clears out the digits.
  107.      * Use before appending them.
  108.      * Typically, you set a series of digits with append, then at the point
  109.      * you hit the decimal point, you set myDigitList.decimalAt = myDigitList.count;
  110.      * then go on appending digits.
  111.      */
  112.     public void clear () {
  113.         decimalAt = 0;
  114.         count = 0;
  115.     }
  116.     /**
  117.      * Appends digits to the list. Ignores all digits over MAX_COUNT,
  118.      * since they are not significant for either longs or doubles.
  119.      */
  120.     public void append (int digit) {
  121.         if (count < MAX_COUNT)
  122.             digits[count++] = (byte) digit;
  123.     }
  124.     /**
  125.      * Utility routine to get the value of the digit list
  126.      * If (count == 0) this throws a NumberFormatException, which
  127.      * mimics Long.parseLong().
  128.      */
  129.     public final double getDouble() {
  130.         if (count == 0) return 0.0;
  131.         StringBuffer temp = new StringBuffer(count);
  132.         temp.append('.');
  133.         for (int i = 0; i < count; ++i) temp.append((char)(digits[i]));
  134.         temp.append('E');
  135.         temp.append(Integer.toString(decimalAt));
  136.         return Double.valueOf(temp.toString()).doubleValue();
  137.         // long value = Long.parseLong(temp.toString());
  138.         // return (value * Math.pow(10, decimalAt - count));
  139.     }
  140.  
  141.     /**
  142.      * Utility routine to get the value of the digit list.
  143.      * If (count == 0) this returns 0, unlike Long.parseLong().
  144.      */
  145.     public final long getLong() {
  146.         // for now, simple implementation; later, do proper IEEE native stuff
  147.  
  148.         if (count == 0) return 0;
  149.  
  150.         // We have to check for this, because this is the one NEGATIVE value
  151.         // we represent.  If we tried to just pass the digits off to parseLong,
  152.         // we'd get a parse failure.
  153.         if (isLongMIN_VALUE()) return Long.MIN_VALUE;
  154.  
  155.         StringBuffer temp = new StringBuffer(count);
  156.         for (int i = 0; i < decimalAt; ++i)
  157.         {
  158.             temp.append((i < count) ? (char)(digits[i]) : '0');
  159.         }
  160.         return Long.parseLong(temp.toString());
  161.     }
  162.  
  163.     /**
  164.      * Return true if the number represented by this object can fit into
  165.      * a long.
  166.      */
  167.     boolean fitsIntoLong(boolean isPositive)
  168.     {
  169.         // Figure out if the result will fit in a long.  We have to
  170.         // first look for nonzero digits after the decimal point;
  171.         // then check the size.  If the digit count is 18 or less, then
  172.         // the value can definitely be represented as a long.  If it is 19
  173.         // then it may be too large.
  174.  
  175.         // Trim trailing zeros.  This does not change the represented value.
  176.         while (count > 0 && digits[count - 1] == (byte)'0') --count;
  177.  
  178.         if (count == 0) return true;
  179.  
  180.         if (decimalAt < count || decimalAt > MAX_COUNT) return false;
  181.  
  182.         if (decimalAt < MAX_COUNT) return true;
  183.  
  184.         // At this point we have decimalAt == count, and count == MAX_COUNT.
  185.         // The number will overflow if it is larger than 9223372036854775807
  186.         // or smaller than -9223372036854775808.
  187.         for (int i=0; i<count; ++i)
  188.         {
  189.             byte dig = digits[i], max = LONG_MIN_REP[i];
  190.             if (dig > max) return false;
  191.             if (dig < max) return true;
  192.         }
  193.  
  194.         // At this point the first count digits match.  If decimalAt is less
  195.         // than count, then the remaining digits are zero, and we return true.
  196.         if (count < decimalAt) return true;
  197.  
  198.         // Now we have a representation of Long.MIN_VALUE, without the leading
  199.         // negative sign.  If this represents a positive value, then it does
  200.         // not fit; otherwise it fits.
  201.         return !isPositive;
  202.     }
  203.  
  204.     private static final boolean DEBUG = false;
  205.  
  206.     /**
  207.      * Set the digit list to a representation of the given double value.
  208.      * This method supports fixed-point notation.
  209.      * @param source Value to be converted; must not be Inf, -Inf, Nan,
  210.      * or a value <= 0.
  211.      * @param maximumFractionDigits The most fractional digits which should
  212.      * be converted.
  213.      */
  214.     public final void set(double source, int maximumFractionDigits)
  215.     {
  216.         set(source, maximumFractionDigits, true);
  217.     }
  218.  
  219.     /**
  220.      * Set the digit list to a representation of the given double value.
  221.      * This method supports both fixed-point and exponential notation.
  222.      * @param source Value to be converted; must not be Inf, -Inf, Nan,
  223.      * or a value <= 0.
  224.      * @param maximumDigits The most fractional or total digits which should
  225.      * be converted.
  226.      * @param fixedPoint If true, then maximumDigits is the maximum
  227.      * fractional digits to be converted.  If false, total digits.
  228.      */
  229.     final void set(double source, int maximumDigits, boolean fixedPoint)
  230.     {
  231.         // Generate a representation of the form DDDDD, DDDDD.DDDDD, or
  232.         // DDDDDE+/-DDDDD.
  233.         String rep = Double.toString(source);
  234.  
  235.         decimalAt = -1;
  236.         count = 0;
  237.         int exponent = 0;
  238.         // Number of zeros between decimal point and first non-zero digit after
  239.         // decimal point, for numbers < 1.
  240.         int leadingZerosAfterDecimal = 0;
  241.         boolean nonZeroDigitSeen = false;
  242.         for (int i=0; i < rep.length(); ++i)
  243.         {
  244.             char c = rep.charAt(i);
  245.             if (c == '.')
  246.             {
  247.             decimalAt = count;
  248.             }
  249.             else if (c == 'e' || c == 'E')
  250.             {
  251.             exponent = Integer.valueOf(rep.substring(i+1)).intValue();
  252.             break;
  253.             }
  254.             else if (count < MAX_COUNT)
  255.             {
  256.             if (!nonZeroDigitSeen)
  257.             {
  258.                 nonZeroDigitSeen = (c != '0');
  259.                 if (!nonZeroDigitSeen && decimalAt != -1) ++leadingZerosAfterDecimal;
  260.             }
  261.  
  262.             if (nonZeroDigitSeen) digits[count++] = (byte)c;
  263.             }
  264.         }
  265.         if (decimalAt == -1) decimalAt = count;
  266.         decimalAt += exponent - leadingZerosAfterDecimal;
  267.  
  268.         if (fixedPoint)
  269.         {
  270.             // The negative of the exponent represents the number of leading
  271.             // zeros between the decimal and the first non-zero digit, for
  272.             // a value < 0.1 (e.g., for 0.00123, -decimalAt == 2).  If this
  273.             // is more than the maximum fraction digits, then we have an underflow
  274.             // for the printed representation.  We recognize this here and set
  275.             // the DigitList representation to zero in this situation.
  276.             if (-decimalAt >= maximumDigits) count = 0;
  277.         }
  278.  
  279.         // Eliminate trailing zeros.
  280.         while (count > 1 && digits[count - 1] == '0')
  281.             --count;
  282.  
  283.         if (DEBUG)
  284.         {
  285.             System.out.print("Before rounding 0.");
  286.             for (int i=0; i<count; ++i) System.out.print((char)digits[i]);
  287.             System.out.println("x10^" + decimalAt);
  288.         }
  289.  
  290.         // Eliminate digits beyond maximum digits to be displayed.
  291.         // Round up if appropriate.
  292.         round(fixedPoint ? (maximumDigits + decimalAt) : maximumDigits);
  293.  
  294.         if (DEBUG)
  295.         {
  296.             System.out.print("After rounding 0.");
  297.             for (int i=0; i<count; ++i) System.out.print((char)digits[i]);
  298.             System.out.println("x10^" + decimalAt);
  299.         }
  300.  
  301.         // The following method also works, and does not rely on the specific
  302.         // format generated by Double.toString().  However, it introduces significant
  303.         // errors in the least-significant digits, which cause round-trip parse and
  304.         // format operations to fail.  We retain this code for future reference;
  305.         // the compiler will ignore it.
  306.         if (false)
  307.         {
  308.             // Find the exponent for this value.  Our convention is 0.mmmm * 10^decimalAt,
  309.             // so we need to add one.
  310.             decimalAt = log10(source) + 1;
  311.  
  312.             // Compute the number of digits to generate based on the maximum fraction
  313.             // digits and the exponent.  For example, if the exponent is -95 and the
  314.             // maximum fraction digits is 100, then we'll have 95 leading zeros and only
  315.             // 5 significant digits.
  316.  
  317.             count = maximumDigits + decimalAt;
  318.             if (count > DBL_DIG) count = DBL_DIG;
  319.             if (count < 0) count = 0;
  320.             if (count == 0) return; // Return if we've underflowed to zero
  321.  
  322.             // Put the mantissa into a long.  We create a mantissa value in the
  323.             // range 10^n-1 <= mantissa < 10^n, where n is the desired number of
  324.             // digits.  If this is a small number << 1, decimalAt may be negative,
  325.             // indicating leading zeros between the decimal point an digits[0]. A
  326.             // decimalAt value of 0 indicates that the decimal point is before
  327.             // digits[0].
  328.  
  329.             //System.out.println("d = " + source + " log = " + (Math.log(source) / LOG10));
  330.             //System.out.println("d == 0.1 " + (source == 0.1));
  331.             long mantissa = Math.round(source * Math.pow(10, count - decimalAt));
  332.             String longRep = Long.toString(mantissa);
  333.  
  334.             // At this point we have a representation of exactly maxDecimalCount
  335.             // characters.
  336.             // FOLLOWING LINE FOR DEBUGGING ONLY.  THIS catches problems with log10 computation.
  337.             if (longRep.length() != count)
  338.             throw new Error("Rep=" + longRep + " rep.length=" + longRep.length() +
  339.                     " exp.len=" + count + " " +
  340.                     "val=" + source + " mant=" + mantissa +
  341.                     " decimalAt=" + decimalAt);
  342.  
  343.             // Eliminate trailing zeros.
  344.             while (count > 1 && longRep.charAt(count - 1) == '0')
  345.             --count;
  346.  
  347.             // Copy digits over
  348.             for (int i=0; i<count; ++i)
  349.             digits[i] = (byte)longRep.charAt(i);
  350.         }
  351.     }
  352.  
  353.     /**
  354.      * Round the representation to the given number of digits.
  355.      * @param maximumDigits The maximum number of digits to be shown.
  356.      * Upon return, count will be less than or equal to maximumDigits.
  357.      */
  358.     private final void round(int maximumDigits)
  359.     {
  360.         // Eliminate digits beyond maximum digits to be displayed.
  361.         // Round up if appropriate.
  362.         if (maximumDigits >= 0 && maximumDigits < count)
  363.         {
  364.             // Check for round to the nearest even.  HShih
  365.             if (digits[maximumDigits] == '5' && digits[maximumDigits-1] != '9' &&
  366.                 (maximumDigits+1 >= count || digits[maximumDigits+1] == '0')) {
  367.                 if (digits[maximumDigits-1] % 2 != 0)
  368.                     ++digits[maximumDigits-1];
  369.             } else if (digits[maximumDigits] >= '5')
  370.             {
  371.                 // Rounding up involved incrementing digits from LSD to MSD.
  372.                 // In most cases this is simple, but in a worst case situation
  373.                 // (9999..99) we have to adjust the decimalAt value.
  374.                 for (;;)
  375.                 {
  376.                     --maximumDigits;
  377.                     if (maximumDigits < 0)
  378.                     {
  379.                         // We have all 9's, so we increment to a single digit
  380.                         // of one and adjust the exponent.
  381.                         digits[0] = '1';
  382.                         ++decimalAt;
  383.                         maximumDigits = 0; // Adjust the count
  384.                         break;
  385.                     }
  386.  
  387.                     ++digits[maximumDigits];
  388.                     if (digits[maximumDigits] <= '9') break;
  389.                     // digits[maximumDigits] = '0'; // Unnecessary since we'll truncate this
  390.                 }
  391.                 ++maximumDigits; // Increment for use as count
  392.             }
  393.             count = maximumDigits;
  394.         }
  395.     }
  396.  
  397.     /**
  398.      * Utility routine to set the value of the digit list from a long
  399.      */
  400.     public final void set(long source)
  401.     {
  402.         set(source, 0);
  403.     }
  404.  
  405.     /**
  406.      * Set the digit list to a representation of the given long value.
  407.      * @param source Value to be converted; must be >= 0 or ==
  408.      * Long.MIN_VALUE.
  409.      * @param maximumDigits The most digits which should be converted.
  410.      * If maximumDigits is lower than the number of significant digits
  411.      * in source, the representation will be rounded.  Ignored if <= 0.
  412.      */
  413.     public final void set(long source, int maximumDigits)
  414.     {
  415.         // for now, simple implementation; later, do proper IEEE stuff
  416.         //        String stringDigits = Long.toString(source);
  417.         String stringDigits = Long.toString(source);
  418.  
  419.         // This method does not expect a negative number. However,
  420.         // "source" can be a Long.MIN_VALUE (-9223372036854775808),
  421.         // if the number being formatted is a Long.MIN_VALUE.  In that
  422.         // case, it will be formatted as -Long.MIN_VALUE, a number
  423.         // which is outside the legal range of a long, but which can
  424.         // be represented by DigitList.
  425.         if (stringDigits.charAt(0) == '-') stringDigits = stringDigits.substring(1);
  426.  
  427.         count = decimalAt = stringDigits.length();
  428.  
  429.         // Don't copy trailing zeros
  430.         while (count > 1 && stringDigits.charAt(count - 1) == '0') --count;
  431.  
  432.             for (int i = 0; i < count; ++i)
  433.                 digits[i] = (byte) stringDigits.charAt(i);
  434.  
  435.         if (maximumDigits > 0) round(maximumDigits);
  436.     }
  437.  
  438.     /**
  439.      * equality test between two digit lists.
  440.      */
  441.     public boolean equals(Object obj) {
  442.         if (this == obj)                      // quick check
  443.             return true;
  444.         if (!(obj instanceof DigitList))         // (1) same object?
  445.             return false;
  446.         DigitList other = (DigitList) obj;
  447.         if (count != other.count ||
  448.         decimalAt != other.decimalAt)
  449.             return false;
  450.         for (int i = 0; i < count; i++)
  451.             if (digits[i] != other.digits[i])
  452.                 return false;
  453.         return true;
  454.     }
  455.  
  456.     /**
  457.      * Generates the hash code for the digit list.
  458.      */
  459.     public int hashCode() {
  460.         int hashcode = decimalAt;
  461.  
  462.         for (int i = 0; i < count; i++)
  463.             hashcode = hashcode * 37 + digits[i];
  464.  
  465.         return hashcode;
  466.     }
  467.  
  468.     /**
  469.      * Returns true if this DigitList represents Long.MIN_VALUE;
  470.      * false, otherwise.  This is required so that getLong() works.
  471.      */
  472.     private boolean isLongMIN_VALUE()
  473.     {
  474.         if (decimalAt != count || count != MAX_COUNT)
  475.             return false;
  476.  
  477.             for (int i = 0; i < count; ++i)
  478.         {
  479.             if (digits[i] != LONG_MIN_REP[i]) return false;
  480.         }
  481.  
  482.         return true;
  483.     }
  484.  
  485.     private static byte[] LONG_MIN_REP;
  486.  
  487.     static
  488.     {
  489.         // Store the representation of LONG_MIN without the leading '-'
  490.         String s = Long.toString(Long.MIN_VALUE);
  491.         LONG_MIN_REP = new byte[MAX_COUNT];
  492.         for (int i=0; i < MAX_COUNT; ++i)
  493.         {
  494.             LONG_MIN_REP[i] = (byte)s.charAt(i + 1);
  495.         }
  496.     }
  497.  
  498.     /**
  499.      * Return the floor of the log base 10 of a given double.
  500.      * This method compensates for inaccuracies which arise naturally when
  501.      * computing logs, and always give the correct value.  The parameter
  502.      * must be positive and finite.
  503.      */
  504.     private static final int log10(double d)
  505.     {
  506.         // The reason this routine is needed is that simply taking the
  507.         // log and dividing by log10 yields a result which may be off
  508.         // by 1 due to rounding errors.  For example, the naive log10
  509.         // of 1.0e300 taken this way is 299, rather than 300.
  510.         double log10 = Math.log(d) / LOG10;
  511.         int ilog10 = (int)Math.floor(log10);
  512.         // Positive logs could be too small, e.g. 0.99 instead of 1.0
  513.         if (log10 > 0 && d >= Math.pow(10, ilog10 + 1))
  514.         {
  515.             ++ilog10;
  516.         }
  517.         // Negative logs could be too big, e.g. -0.99 instead of -1.0
  518.         else if (log10 < 0 && d < Math.pow(10, ilog10))
  519.         {
  520.             --ilog10;
  521.         }
  522.         return ilog10;
  523.     }
  524.  
  525.     private static final double LOG10 = Math.log(10.0);
  526.  
  527.     public String toString()
  528.     {
  529.         if (isZero()) return "0";
  530.         StringBuffer buf = new StringBuffer("0.");
  531.         for (int i=0; i<count; ++i) buf.append((char)digits[i]);
  532.         buf.append("x10^");
  533.         buf.append(decimalAt);
  534.         return buf.toString();
  535.     }
  536. }
  537.